package scau.zxck.view.controller;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import scau.zxck.entity.Connection;
import scau.zxck.utils.DatabaseUtil;
import scau.zxck.utils.ViewUtil;
import scau.zxck.view.Main;
import scau.zxck.view.stage.AlertStage;

/**
 * Created by chenyulin on 2016/11/29.
 */
public class EditConnController {

    @FXML private TextField tfConnName;
    @FXML private TextField tfHost;
    @FXML private TextField tfUserName;
    @FXML private TextField tfPassword;
    @FXML private TextField tfPort;
    private int selectedIndex;
    private Connection selectedConn;

    public void initialize() {
        selectedIndex = Main.connTreeController.getSelectedItem().getConnIndex();
        selectedConn = Main.connectionList.get(selectedIndex);
        tfConnName.setText(selectedConn.getConnName());
        tfHost.setText(selectedConn.getHost());
        tfUserName.setText(selectedConn.getUserName());
        tfPassword.setText(selectedConn.getPassword());
        tfPort.setText(selectedConn.getPort());
    }

    @FXML
    public void btTestAction() {
        String connName = tfConnName.getText();
        String host = tfHost.getText();
        String userName = tfUserName.getText();
        String password = tfPassword.getText();
        String port = tfPort.getText();
        Connection conn = new Connection(connName, host, userName, password, port);
        if(DatabaseUtil.testConnection(conn))
            new AlertStage("Connect Successfully").show();
        else
            new AlertStage("Error", "Failed to connect").show();
    }

    @FXML
    public void btSaveAction() {
        String connName = tfConnName.getText();
        String host = tfHost.getText();
        String userName = tfUserName.getText();
        String password = tfPassword.getText();
        String port = tfPort.getText();
        Connection connToReg = new Connection(connName, host, userName, password, port);
        if (NewConnController.regInfo(connToReg)) {
            selectedConn.setConnName(connName);
            selectedConn.setHost(host);
            selectedConn.setUserName(userName);
            selectedConn.setPassword(password);
            selectedConn.setPort(port);
            Main.connTreeController.initialize();
            ViewUtil.writeInfoToConfigFile();
            Main.configConnStage.close();
        }
    }
}
